package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    /**
     * 作用： 下单  (本质：把购物车的数据转换为一个Orders 与多个OrderDetail)
     *
     * @param orders 订单的信息（地址id，支付方式，备注）
     * @return
     * @Param userId  当前的登陆者
     */
    @Override
    @Transactional
    public void submit(Orders orders, Long userId) {
        //根据当前用户id，查询购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartByUserId(userId);
        //根据用户id，查询用户数据
        User user = userMapper.findById(userId);
        //根据地址id，查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        //订单的id
        Long orderId = UUIDUtils.getUUIDInOrderId().longValue();
        //声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");
        //D. 遍历所有的购物像， 一个购物项就是一个订单明细， 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue()); //订单项目的主键
            orderDetail.setName(shoppingCart.getName());  //购物项的菜品的名字
            orderDetail.setOrderId(orderId); //订单项所属的订单的id
            orderDetail.setDishId(shoppingCart.getDishId()); //购物项的菜品的id
            orderDetail.setSetmealId(shoppingCart.getSetmealId()); //购物项的套餐的id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor()); //口味
            orderDetail.setNumber(shoppingCart.getNumber());  //数量
            orderDetail.setAmount(shoppingCart.getAmount()); //单价
            orderDetail.setImage(shoppingCart.getImage()); //
            //计算每一项物品的总价
            BigDecimal amount = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber() + ""));
            totalAmount = totalAmount.add(amount);
            orderDetailList.add(orderDetail);
        }
        //组装订单数据，批量保存订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setStatus(1);//状态
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now().plusDays(7L));
        orders.setAmount(totalAmount);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //插入订单
        orderMapper.save(orders);
        //批量插入订单
        orderDetailMapper.Batch(orderDetailList);
        //删除当前用户购物车列表
        shoppingCartMapper.clean(userId);
    }

    /*订单分页查询*/
    @Override
    public Page<Orders> page(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        //设置当前页，分页大小
        PageHelper.startPage(page, pageSize);
        //查询数据，得到的是list<orders>
        List<Orders> ordersList = orderMapper.findByNumber(number, beginTime, endTime);
        //得到pageInfo对象，里面储存的是orders
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);
        //封装到page对象
        Page<Orders> ordersPage = new Page<>(ordersPageInfo.getList(), ordersPageInfo.getTotal(), page, pageSize);
        return ordersPage;
    }

    //历史订单分页查询
    @Override
    public Page<Orders> userPage(Integer page, Integer pageSize,Long number) {
        //设置分页大小
        PageHelper.startPage(page,pageSize);
        //查询数据，得到的是list<orders>
        List<Orders> ordersList = orderMapper.findOrders();
        //得到PageInfo对象，里面是orders
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);
        //封装到Page对象
        Page<Orders> ordersPage = new Page<>(ordersPageInfo.getList(), ordersPageInfo.getTotal(), page, pageSize);
        return ordersPage;
    }
}
